#ifndef __PROCESS_POOL_HPP__
#define __PROCESS_POOL_HPP__

#include "Task.hpp"
#include <iostream>
#include <vector>
#include <string>
#include <unistd.h>
#include <cstdlib>
#include <sys/wait.h>

class Channel
{
public:
    Channel(int wfd, pid_t subid) : _wfd(wfd), _subid(subid)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(_subid);
    }

    void Send(int taskcode)
    {
        int n = write(_wfd, &taskcode, sizeof(taskcode));
        (void)n;
    }
    int Fd() { return _wfd; }
    pid_t Subid() { return _subid; }
    std::string Name() { return _name; }

    void Close()
    {
        close(_wfd);
    }

    void Wait()
    {
        waitpid(_subid, nullptr, 0);
    }

    ~Channel() {}

private:
    int _wfd;     // 写端文件描述符
    pid_t _subid; // 子进程的id
    std::string _name;
};

class ChannelManger
{
public:
    ChannelManger() : _next(0)
    {
    }

    void Insert(int wfd, pid_t id)
    {
        _channels.emplace_back(wfd, id);
    }

    Channel &Select()
    {
        auto &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }

    void CloseAll()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
        }
    }

    void StopSubProcess()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
            std::cout << "关闭" << channel.Name() << std::endl;
        }
    }

    void WaitSubProcess()
    {
        for (auto &channel : _channels)
        {
            channel.Wait();
            std::cout << "回收" << channel.Name() << std::endl;
        }
    }

    void CloseAndWait()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
            std::cout << "关闭" << channel.Name() << std::endl;
            channel.Wait();
            std::cout << "回收" << channel.Name() << std::endl;
        }
    }

    ~ChannelManger() {}

private:
    std::vector<Channel> _channels;
    int _next;
};

const int gdefaultnum = 5;

class ProcessPool
{
public:
    ProcessPool(int num) : _process_num(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(Upload);
        _tm.Register(Updown);
    }

    void Work(int rfd)
    {
        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                    continue;
                std::cout << "子进程[" << getpid() << "]" << "收到任务码:" << code << std::endl;
                _tm.Execute(code);
            }
            else if (n == 0)
            {
                std::cout << "子进程退出" << std::endl;
                break;
            }
            else
            {
                std::cout << "读取错误" << std::endl;
                break;
            }
        }
    }

    void Run()
    {
        // 1.随机选择一个任务
        int taskcode = _tm.Code();

        // 2.选择信道
        auto &c = _cm.Select();
        std::cout << "选择了一个子进程" << c.Name() << std::endl;

        // 发送任务
        c.Send(taskcode);
        std::cout << "发送了一个任务码" << taskcode << std::endl;
    }

    bool Start()
    {
        for (int i = 0; i < _process_num; ++i)
        {
            // 1. 创建管道
            int fds[2] = {0};
            int n = pipe(fds);
            if (n < 0)
                return false;

            // 2. 创建子进程
            pid_t id = fork();
            if (id == 0) // child
            {
                // 关闭继承的写端
                _cm.CloseAll();
                // 关闭写端
                close(fds[1]);
                Work(fds[0]); // 从读端读取数据
                close(fds[0]);
                exit(0);
            }
            else if (id > 0) // father
            {
                close(fds[0]); // 关闭读端
                _cm.Insert(fds[1], id);
            }
            else
            {
                return false;
            }
        }
        return true;
    }

    void Stop()
    {
        // // 关闭父进程的写端
        // _cm.StopSubProcess();
        // // 回收子进程
        // _cm.WaitSubProcess();
        _cm.CloseAndWait();
    }

    ~ProcessPool() {}

private:
    ChannelManger _cm;
    int _process_num;
    TaskManger _tm;
};

#endif